package com.another.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.another.common.utils.common.EmptyUtil;
import com.another.common.utils.result.Result;
import com.another.common.utils.uuid.UUIDFactory;
import com.another.gateway.util.ApiPath;
import com.another.gateway.util.AsyncLog;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpMethod;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.nio.charset.Charset;


public class LogFilter extends ZuulFilter {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AsyncLog asyncLog;

    @Autowired
    private ApiPath apiPath;


    @Override
    public String filterType() {
        /**
         * pre：可以在请求被路由之前调用
         * route：在路由请求时候被调用
         * post：在route和error过滤器之后被调用
         * error：处理请求时发生错误时被调用
         */
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 1;
    }


    //过滤请求不需要处理的URL请求，返回false
    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

            logger.info("==============================日志记录==============================");
//url
        logger.info("url=" + request.getRequestURL());

        //methon
        logger.info("method=" + request.getMethod());

        //ip
        logger.info("ip=" + request.getRemoteHost());


        logger.info("请求方法:" + request.getMethod());

        //预处理请求不需要处理
        if (!request.getMethod().equals(HttpMethod.OPTIONS.name())) {

            //截取url
            String baseUrl = request.getRequestURI();
            String url = baseUrl.substring(baseUrl.indexOf("/", 1), baseUrl.length());
            if (StringUtils.isNotBlank(url)
                    && url.indexOf("import") > -1) {
                return null;
            }




            //获取返回值
            RequestContext context = RequestContext.getCurrentContext();
            try {
                // 获取返回值内容，加以处理
                InputStream stream = context.getResponseDataStream();
                String body = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));

                Result rst = new Result();

                //判断其他验证是否已经抛异常
                if (EmptyUtil.isEmpty(body)) {
                    rst=JSON.parseObject(ctx.getResponseBody(), Result.class);
                    rst.setAccessId(UUIDFactory.getUUID());

                    return null;


                }else{
                    rst = JSON.parseObject(body, Result.class);
                }

                //生成访问id
                rst.setAccessId(UUIDFactory.getUUID());



                //判断返回值是否是异常
                if (EmptyUtil.isEmpty(rst)||EmptyUtil.isEmpty(rst.getCode())) {
                    context.setResponseBody(body);
                }else {




                    //你的处理逻辑，加密，添加新的返回值等等.....


                    // 内容重新写入
                    context.setResponseBody(JSON.toJSONString(rst));


                    //查看是否需要记录日志到数据库
                    if (apiPath.getLogPath().contains(url)) {
                        asyncLog.saveLog(request, rst.getAccessId());
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.info(e.getMessage(), e);
                context.setResponseBody(JSON.toJSONString(Result.error("请求出错!")));
            }


            logger.info("==============================日志记录结束==============================");
        }else{

            return true;
        }


        return null;
    }



    private void returnResponse(RequestContext ctx, String message) {
        ctx.getResponse().setHeader("Content-Type", "application/json;charset=UTF-8");
        ctx.getResponse().setCharacterEncoding("UTF-8");
        //ctx.setSendZuulResponse(true);
        //ctx.setResponseStatusCode(200);
        //过滤该请求，不进行路由
        ctx.setSendZuulResponse(false);
        //设置返回的错误码
        ctx.setResponseStatusCode(401);
        //设置返回的消息
        ctx.setResponseBody(message);
    }
}
